package com.doge.walknovel.business.home.profile.viewed

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelInfo
import com.doge.walknovel.api.model.process
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.ActivityViewedHistoryBinding

class ViewedHistoryActivity : BaseActivity() {
    private val binding by lazy { ActivityViewedHistoryBinding.inflate(layoutInflater) }

    private val viewModel: ViewedHistoryViewModel by viewModels { ViewedHistoryViewModelFactory() }
    private val adapter by lazy { ViewedHistoryAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.request()
        }
        viewModel.loading.observe(this) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(this) {
            adapter.submitList(it)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.request()
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> (item as? NovelInfo?).process(this, NovelRefer.history)
        }
    }

    companion object {
        fun start(context: Context) {
            AccountHelper.requiredLogin {
                context.startActivity(Intent(context, ViewedHistoryActivity::class.java))
            }
        }
    }
}